package com.hqyj.callback;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 项目:rabbitmq-230301-provider
 * 描述:
 * 时间:2023/8/4 15:48
 * 作者:admin
 * 版本:1.0
 **/

@Component
@Slf4j
public class ShopMqConfirm  implements RabbitTemplate.ConfirmCallback {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @SneakyThrows
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if(b){

            //取出消息,json字符串格式
            String json= correlationData.getId();
            //把json字符串格式转成map对象
            ObjectMapper objectMapper = new ObjectMapper();
            Map m = objectMapper.readValue(json,Map.class);
            //取出库存,减一
            int num = (Integer) m.get("stock")-1;
            //存入更新后的库存
            redisTemplate.opsForValue().set("stock:"+m.get("shopName"),num,30, TimeUnit.MINUTES);
            log.info("更新商品{}的库存为{}",m.get("shopName"),num);
            //标识这个用户购买这个商品了
            redisTemplate.opsForHash().put("kill:"+m.get("shopName"),m.get("userName"),1);
            //删除锁减
            redisTemplate.delete("suo:"+m.get("shopName"));

        }
    }
}
